import json
import logging
import os
import platform
import random
import re
import time
import traceback
from datetime import datetime

import requests
from playwright.sync_api import Page, sync_playwright

# from pythonTryEverything.putdonwphone.data import englisword
########################################################################


class MyKuaishou:
    def __init__(self, cookies_path: str, login_url: str, upload_url: str):
        self.driver = None
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_url = upload_url
        # playwright 部分
        self.browser = None
        print("creae MyKuaishou")

    def __del__(self):
        if self.driver:
            self.driver.close()
        print("is being destroyed")

    def upload_picture(self, picture_path: str, msg: str):
        """start instance"""
        with sync_playwright() as playwright:
            # 01 启动chomue浏览器
            # playwright执行默认运行的浏览器是chromium！
            # 全局代理
            display_headless = False
            if platform.system() == "Linux":
                display_headless = True
                self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(
                    channel="chrome", headless=display_headless
                )
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, msg)
            self.browser.close()

    # 登录 设置代理
    def login_or_restore_cookies(self) -> Page:
        # 创建一个新的页面
        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.21 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
        context = self.browser.new_context(user_agent=user_agent)
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("cookies is exited load")
            # 从文件中加载 cookies
            with open(self.cookies_path, "r", encoding="utf-8") as myfile:
                cookies = json.load(myfile)
            # 将 cookies 加载到页面中
            context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 相信第一次接触Playwright的同学，一定会对Browser、 BrowserContext 和Page这三个概念所困
            # https://blog.csdn.net/liwenxiang629/article/details/130810265
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(30)
            # 获取当前页面的 cookies
            cookies = page.context.cookies()
            print(cookies)
            # 保存 cookies 到文件
            with open(self.cookies_path, "w", encoding="utf-8") as myfile:
                myfile.write(json.dumps(cookies))
        return page

    # 登录
    def msg_up_load(self, page: Page, picture_path: str, msg: str):
        page.goto(self.upload_url)
        time.sleep(3)
        # https://playwright.dev/docs/locators
        # 使用 XPath 表达式定位元素
        xpath_expression = '//div[contains(text(), "上传图文")]'
        example_element = page.locator("xpath=//div[contains(text(), '上传图文')]")
        example_element.click()
        print("进入图文页面")
        time.sleep(2)

        # 点击选择文件，输入文件
        with page.expect_file_chooser() as fc_info:
            # 找到拖拽区域
            page.click("xpath=//button[contains(text(), '上传图片')]")
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path)

        time.sleep(3)
        page.mouse.down()
        page.mouse.down()

        # 填写描述
        page.locator("css=.iGOvMbhp8tU-").fill(msg)
        time.sleep(3)
        print("填写描述")

        # 添加音乐
        page.get_by_placeholder("搜索音乐、歌手、歌词添加至作品").click()
        time.sleep(5)
        index = random.randint(0, 5)
        page.locator("xpath=//button[./span[text()='添加']]").locator(
            "nth={}".format(index)
        ).click()
        time.sleep(5)

        # 添加地点
        page.mouse.down()
        page.mouse.down()
        page.wait_for_timeout(500)
        # 发布
        page.locator("xpath=//button[./span[text()='发布']]").click()
        print("发布")
        time.sleep(7)

    # 登录
    def auto_upload_mp4(
        self, page: Page, local_file_path, artile_title, artile_content
    ):
        """_summary_

        Args:
            page (Page): _description_
            picture_path (str): _description_
            msg (str): _description_
        """
        page.goto(self.upload_url)
        page.wait_for_timeout(1000)

        # https://playwright.dev/docs/locators
        # 使用 XPath 表达式定位元素
        page.locator("xpath=//div[contains(text(), '上传视频')]").click()
        print("上传视频")
        page.wait_for_timeout(1000)

        # 点击选择文件，输入文件
        with page.expect_file_chooser() as fc_info:
            # 找到拖拽区域
            page.click("xpath=//button[contains(text(), '上传视频')]")
        file_chooser = fc_info.value
        file_chooser.set_files(local_file_path)

        if platform.system() == "Windows":
            page.wait_for_timeout(120 * 1000)
        else:
            page.wait_for_timeout(10 * 1000)
        page.mouse.down()
        page.mouse.down()

        print("上传视频完成")

        # 填写描述
        page.get_by_placeholder("添加合适的话题和描述，作品能获得更多推荐～").fill(
            artile_content
        )
        page.mouse.down()
        page.wait_for_timeout(1000)
        print("添加合适的话题和描述，作品能获得更多推荐～")

        # 所属领域
        page.mouse.down()
        page.mouse.down()
        # page.locator("#rc_select_0").click()
        # page.wait_for_timeout(1000)
        # page.get_by_text("个人观点，仅供参考").click()
        page.wait_for_timeout(1000)

        try:
            # fraem is same page
            page.get_by_text("下一步").click()
            page.mouse.down()
            page.wait_for_timeout(1000)
            page.mouse.down()
            page.locator("#react-joyride-portal div").first.click()
            page.wait_for_timeout(1000)
            page.mouse.down()
            page.get_by_text("下一步").click()
            page.wait_for_timeout(1000)
            page.mouse.down()
            page.get_by_role("button", name="Skip").click()
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")
        # 发布
        # page.locator("xpath=//button[./span[text()='发布']]").click()
        page.get_by_text("发布", exact=True).click()
        print("发布")
        page.wait_for_timeout(8 * 1000)

    def upload_mp4(self, local_file_path, artile_title, artile_content):
        """远离手机"""
        with sync_playwright() as playwright:
            # 01 启动chomue浏览器
            # playwright执行默认运行的浏览器是chromium！
            # 全局代理
            display_headless = False
            # display_headless = True
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(headless=display_headless)

            # 模拟登录
            login_page = self.login_or_restore_cookies()
            self.auto_upload_mp4(
                login_page, local_file_path, artile_title, artile_content
            )
            self.browser.close()


def interface_auo_upload_mp4_kuaishou(local_file_path, artile_title, artile_content):
    try:
        sys = platform.system()
        login_url = "https://cp.kuaishou.com/profile"
        upload_url = "https://cp.kuaishou.com/article/publish/video?tabType=1"
        if sys == "Windows":
            cookies_path = r"D:\mp4\etc\kuaishou_small.json"
        elif sys == "Darwin":
            cookies_path = r"/Users/wangchuanyi/mp4/etc/kuaishou_small.json"
        else:
            cookies_path = r"/root/bin/mykuaishou.json"

        autoupload = MyKuaishou(cookies_path, login_url, upload_url)
        # 优化标题：
        if len(artile_title) == 0:
            artile_title = os.path.basename(local_file_path)
            artile_title = artile_title.split(".")[0]

        artile_content += " #日拱一卒无有尽，功不唐捐终入海" + "\r\n"
        if len(artile_content) > 408:
            artile_content = artile_content[:407]
        autoupload.upload_mp4(local_file_path, artile_title, artile_content)
    except ValueError:
        print("Could not convert data to an integer.")
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        print(traceback.format_exc())


if __name__ == "__main__":

    # 自动发表mp4内容
    local_file_path = r"/Users/wangchuanyi/mp4/book/1.mp4"
    artile_title = "笔记:早起的奇迹"
    artile_content = """
克服赖床方法：睡前积极暗示：期待第二天精力充沛地醒来。
1. 闹钟放远：迫使自己下床。
2. 起床刷牙：醒神。
3. 喝水补水：对抗疲劳。
4. 穿上运动服：为后续活动做准备
#do书 #每天听本书
"""
    interface_auo_upload_mp4_kuaishou(local_file_path, artile_title, artile_content)
    # playwright codegen "https://cp.kuaishou.com/article/publish/video?tabType=1"
